<template>
  <div class="comment-section">
    <!-- 评论输入框 -->
    <div class="comment-input">
      <el-input
        v-model="commentContent"
        type="textarea"
        :rows="2"
        :placeholder="replyTo ? '回复评论...' : '写下你的评论...'"
      />
      <div class="comment-actions">
        <el-button 
          type="primary" 
          @click="submitComment"
          :disabled="!commentContent.trim()"
        >
          {{ replyTo ? '回复' : '发表评论' }}
        </el-button>
        <el-button v-if="replyTo" @click="cancelReply">取消回复</el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <el-empty v-if="comments.length === 0" description="暂无评论" />
      <template v-else>
        <div v-for="comment in comments" :key="comment._id" class="comment-item">
          <!-- 主评论 -->
          <div class="comment-main">
            <el-avatar :size="40" :src="comment.userId.avatar">
              {{ comment.userId.username.charAt(0) }}
            </el-avatar>
            <div class="comment-content">
              <div class="comment-header">
                <span class="username">{{ comment.userId.username }}</span>
                <span class="time">{{ formatTime(comment.createdAt) }}</span>
              </div>
              <p class="text">{{ comment.content }}</p>
              <div class="comment-footer">
                <el-button text @click="showReplyInput(comment)">回复</el-button>
                <el-button 
                  v-if="canDelete(comment)" 
                  text 
                  type="danger" 
                  @click="deleteComment(comment._id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>

          <!-- 回复列表 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
            <div v-for="reply in comment.replies" :key="reply._id" class="reply-item">
              <div class="comment-main">
                <el-avatar :size="32" :src="reply.userId.avatar">
                  {{ reply.userId.username.charAt(0) }}
                </el-avatar>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="username">{{ reply.userId.username }}</span>
                    <span class="time">{{ formatTime(reply.createdAt) }}</span>
                  </div>
                  <p class="text">{{ reply.content }}</p>
                  <div class="comment-footer">
                    <el-button text @click="showReplyInput(comment)">回复</el-button>
                    <el-button 
                      v-if="canDelete(reply)" 
                      text 
                      type="danger" 
                      @click="deleteComment(reply._id)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useStore } from 'vuex';

const props = defineProps({
  targetType: {
    type: String,
    required: true,
    validator: value => ['notice', 'topic', 'activity', 'market', 'post'].includes(value)
  },
  targetId: {
    type: String,
    required: true
  }
});

const store = useStore();
const commentContent = ref('');
const replyTo = ref(null);
const comments = computed(() => store.state.comments);

// 加载评论列表
const loadComments = async () => {
  try {
    await store.dispatch('fetchComments', {
      targetType: props.targetType,
      targetId: props.targetId
    });
  } catch (error) {
    ElMessage.error('加载评论失败');
  }
};

// 提交评论
const submitComment = async () => {
  try {
    await store.dispatch('addComment', {
      targetType: props.targetType,
      targetId: props.targetId,
      content: commentContent.value,
      replyTo: replyTo.value?._id
    });
    
    ElMessage.success('评论成功');
    commentContent.value = '';
    replyTo.value = null;
  } catch (error) {
    ElMessage.error('评论失败');
  }
};

// 显示回复输入框
const showReplyInput = (comment) => {
  replyTo.value = comment;
  commentContent.value = '';
};

// 取消回复
const cancelReply = () => {
  replyTo.value = null;
  commentContent.value = '';
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await store.dispatch('deleteComment', {
      commentId,
      targetType: props.targetType,
      targetId: props.targetId
    });
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 检查是否可以删除评论
const canDelete = (comment) => {
  const currentUser = store.getters.currentUser;
  return currentUser && (
    currentUser.role === 'admin' || 
    comment.userId._id === currentUser._id
  );
};

// 格式化时间
const formatTime = (date) => {
  return formatDistanceToNow(new Date(date), {
    addSuffix: true,
    locale: zhCN
  });
};

onMounted(() => {
  loadComments();
});
</script>

<style scoped>
.comment-section {
  margin: 20px 0;
}

.comment-input {
  margin-bottom: 20px;
}

.comment-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 20px;
}

.comment-main {
  display: flex;
  gap: 12px;
  margin-bottom: 10px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.time {
  color: #909399;
  font-size: 12px;
}

.text {
  margin: 8px 0;
  color: #606266;
  line-height: 1.5;
}

.comment-footer {
  display: flex;
  gap: 12px;
}

.replies-list {
  margin-left: 52px;
  margin-top: 10px;
}

.reply-item {
  margin-bottom: 12px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
